// select.js —— 选集页：从 sessionStorage / 接口拿数据 -> 规范化 -> 渲染按钮
document.addEventListener("DOMContentLoaded", async () => {
  const cfg     = window.SELECT_CONFIG || {};
  const epList  = document.getElementById("epList");
  const titleEl = document.getElementById("selTitle");
  const metaEl  = document.getElementById("selMeta");
  const coverEl = document.getElementById("selCover");
  const descEl  = document.getElementById("selDesc");

  // 1) 优先从 sessionStorage 取（由列表页跳转时写入）
  let payload = safeParse(sessionStorage.getItem("EP_SELECT_PAYLOAD"));
  const qsId = new URLSearchParams(location.search).get("id");

  // 2) 无缓存则兜底拉取（可选：你如果没有这个后端，就可以删掉这一段）
  if ((!payload || !Array.isArray(payload.episodes) || !payload.episodes.length) && qsId) {
    try {
      const url = withQuery(cfg.episodesApi || "/api/video_episodes/", { id: qsId });
      const res = await fetch(url);
      const data = await res.json();
      if (data && data.ok) {
        payload = {
          seriesId: qsId,
          title: data.title || "",
          cover: data.cover_url || "",
          author: data.author || "",
          desc: data.desc || "",
          episodes: data.episodes || []
        };
      }
    } catch (e) {
      console.error("episodes fetch failed", e);
    }
  }

  // 3) 判空
  if (!payload) {
    renderEmpty("未找到选集", "请从列表页重新进入");
    return;
  }

  // 4) 头部信息
  titleEl && (titleEl.textContent = payload.title || "未命名视频");
  const meta = [];
  if (payload.author) meta.push(payload.author);
  if (payload.seriesId) meta.push("ID: " + payload.seriesId);
  metaEl  && (metaEl.textContent = meta.join(" · "));
  coverEl && payload.cover && (coverEl.src = payload.cover);
  descEl  && payload.desc  && (descEl.textContent = payload.desc);

  // 5) 规范化 episodes 后渲染
  const eps = normalizeEpisodes(payload.episodes);
  if (!eps.length) {
    renderEmpty("暂无选集数据", "后端未返回可用的集数列表");
    return;
  }
  renderEpisodes(eps);

  // ========== Helpers ==========
  function normalizeEpisodes(raw) {
    // 后端有时会把列表当成字符串（甚至是单引号的 Python repr），这里做兜底
    if (typeof raw === "string") {
      let s = raw.trim();
      try {
        // 优先直接 JSON.parse
        return normalizeEpisodes(JSON.parse(s));
      } catch {
        try {
          // 把单引号换成双引号再试（简单兜底，不处理转义的极端场景）
          return normalizeEpisodes(JSON.parse(s.replace(/'/g, '"')));
        } catch {
          console.warn("episodes 不是合法 JSON：", s);
          return [];
        }
      }
    }
    if (!Array.isArray(raw)) return [];

    // 统一为 { ep, title, url }
    return raw.map((e, i) => {
      const idx   = toInt(e?.ep ?? e?.id) || (i + 1);
      const title = (e && (e.title || e.name)) || `第${idx}集`;
      const url   = (e && e.url) || "";
      return { ep: idx, title, url };
    }).filter(e => e && typeof e.title === "string"); // 保守过滤
  }

  function renderEpisodes(list) {
    if (!epList) return;

    // 只渲染“选择”按钮，不自动播放
    epList.innerHTML = list.map((ep) => {
      const epName = escapeHTML(ep.title);
      const sub    = ep.ep ? `第 ${ep.ep} 集` : "";
      return `
        <button class="ep-btn" data-url="${escapeAttr(ep.url || "")}" data-title="${escapeAttr(epName)}">
          <div class="ep-title">${epName}</div>
          ${sub ? `<div class="ep-sub">${sub}</div>` : ""}
        </button>
      `;
    }).join("");

    // 点击只是高亮选择，如果你要“点按钮就跳到播放页”，在这里写跳转逻辑即可
    epList.querySelectorAll(".ep-btn").forEach(btn => {
      btn.addEventListener("click", () => {
        epList.querySelectorAll(".ep-btn").forEach(b => b.classList.remove("active"));
        btn.classList.add("active");
        const url = btn.dataset.url || "";
        const t   = btn.dataset.title || "";
        console.log("选择了：", t, url);
        // 如果要跳播放页：window.location.href = `/play?src=${encodeURIComponent(url)}&t=${encodeURIComponent(t)}`;
      });
    });
  }

  function renderEmpty(title, subtitle) {
    titleEl && (titleEl.textContent = title || "未找到选集");
    metaEl  && (metaEl.textContent  = subtitle || "");
    epList  && (epList.innerHTML = `<div class="alert alert-warning w-100">${escapeHTML(subtitle || "暂无数据")}</div>`);
  }

  function safeParse(s) {
    try { return JSON.parse(s || ""); } catch { return null; }
  }

  function withQuery(base, obj) {
    const u = new URL(base, location.origin);
    Object.entries(obj || {}).forEach(([k, v]) => (v != null) && u.searchParams.set(k, v));
    return u.toString();
  }

  function toInt(v) {
    const n = parseInt(v, 10);
    return Number.isFinite(n) ? n : 0;
  }

  function escapeHTML(s) {
    return String(s || "").replace(/[&<>"']/g, m => ({
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    }[m]));
  }

  function escapeAttr(s) {
    // 用于 HTML 属性；这里简单同 escapeHTML
    return escapeHTML(s);
  }
});
